package com.im.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.im.app.authConfig.CurrentUser;
import com.im.app.authConfig.RequireLogin;
import com.im.app.model.*;
import com.im.app.service.*;
import com.im.app.utils.ExcelUtil;
import com.im.app.utils.Response;
import com.im.app.utils.ResponseResult;
import com.im.app.utils.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tio.utils.hutool.DateUnit;
import org.tio.utils.hutool.DateUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "/statistics")
public class StatisticsController {

    @Resource
    private IUserService userService;

    @Resource
    private ICodeService codeService;

    @Resource
    private ChatLogsService chatLogsService;

    @Resource
    private StatisticsService statisticsService;

    @Resource
    private KuaijieService kuaijieService;

    @Resource
    private LixianService lixianService;

    @Resource
    private WelcomeService welcomeService;

    @Resource
    private IYunConfigService iYunConfigService;
    /**
     * 查询今日访客
     *
     * @author aaa
     * @date 2023-04-12
     */
    @RequireLogin
    @GetMapping("/getTodayVisitor")
    public ResponseResult<Object> getTodayVisitor(@CurrentUser User user){
        //访客数量
        int visitorCount = userService.getTodayVisitor(user.getUserId());
        //消息记录数量
        int chatLogsCount = chatLogsService.getTodayChatLogs(user.getUserId());
        Map map = new HashMap();
        map.put("visitorCount",visitorCount);
        map.put("chatLogsCount",chatLogsCount);
        return Response.makeOKRsp(map);
    }

    /**
     * 单页面访客数量 最近5天的访客
     *
     * @author aaa
     * @date 2023-04-12
     */
    @GetMapping("/getSumVisitor")
    public ResponseResult<Object> getSumVisitor(String codes){
        if (codes == null) return Response.makeErrRsp("卡密不能为空");
        String[] KaMiCodes = codes.split(",");
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        for (String code: KaMiCodes) {
            code = code.trim();
            User user = userService.getUserBykamiCode(code);
            if (user != null){
                int count = userService.getTodayVisitor(user.getUserId());
                //更新当天
                int result = updateStatistics(user, count);
                if(result>0){
                    List<Map<String,Object>> statistics = statisticsService.selectStatisticsByKaMi(code);
                    map.put(code,statistics);
                }
            }else{
                List<Map<String,Object>> mapList = new ArrayList<>();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                for(int i = 0 ; i< 5 ; i++){
                    Map<String, Object> dateMap = new HashMap<>();
                    Date date = DateUtils.addDays(new Date(), -i);
                    String format = simpleDateFormat.format(date);
                    dateMap.put("tongjidate",format);
                    dateMap.put("counts",0);
                    mapList.add(dateMap);
                }
                map.put(code,mapList);
            }
        }
        return Response.makeOKRsp(map);
    }


     private int updateStatistics(User user,Integer count){
         String curDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
         Statistics statistics = statisticsService.selectStatisticsByDate(user.getUserId(),curDate);
         int result;
         if(null == statistics){
             Statistics st = new Statistics();
             st.setTongjidate(curDate);
             st.setCounts(Long.valueOf(count));
             st.setUseId(user.getUserId());
             st.setUserkami(user.getKamicode());
             result = statisticsService.insertStatistics(st);
         }else{
             statistics.setCounts(Long.valueOf(count));
             result = statisticsService.updateStatistics(statistics);
         }
        return result;
     }

    @GetMapping("exportExcel")
    public void export(String kamicode,String date, HttpServletResponse response){
        User kefuUser = userService.getUserBykamiCode(kamicode);
        if(null != kefuUser){
            List<User> userList = userService.getUserByKefuId(kefuUser.getUserId(),date);
            //导出操作
            ExcelUtil.exportExcel(userList,kamicode+"-"+date+"-客户信息","sheet1",User.class,kamicode+"-"+date+"-客户信息.xls",response);
        }
    }

    @GetMapping("/exportQuery")
    public ResponseResult<Object> exportQuery(String kamicode,String date){
        User kefuUser = userService.getUserBykamiCode(kamicode);
        if(null != kefuUser){
            List<User> userList = userService.getUserByKefuId(kefuUser.getUserId(),date);
            return Response.makeOKRsp(userList);
        }
        return Response.makeErrRsp("卡密信息错误");
    }

    /**
     *卡密复制
     *
     * */
    @GetMapping("/copyInfo")
    public ResponseResult<Object> copyInfo(String kamicode,String copyKamicodes){

        if (kamicode == null || copyKamicodes == null) return Response.makeErrRsp("卡密不能为空");
        String[] copys = copyKamicodes.split(",");
        User user = userService.getUserBykamiCode(kamicode);
        if(null == user){
           return Response.makeErrRsp("卡密信息错误");
        }
        for (String copy : copys) {
            User copyUser = userService.getUserBykamiCode(copy);
            if(copyUser == null){
               return Response.makeErrRsp("被复制卡密信息错误");
            }
            copyUser.setAvatar(user.getAvatar());
            copyUser.setName(user.getName());
            userService.updateById(copyUser);
            //复制快捷语
//            kuaijieService.deleteByUserId(copyUser.getUserId());
            List<Kuaijie> kuaijies = kuaijieService.queryKuaijieList(user.getUserId());
            for (Kuaijie kuaijie : kuaijies) {
                Kuaijie  newKuaijie = new Kuaijie();
                newKuaijie.setUserId(copyUser.getUserId());
                newKuaijie.setIsuse(kuaijie.getIsuse());
                newKuaijie.setName(kuaijie.getName());
                newKuaijie.setContent(kuaijie.getContent());
                newKuaijie.setPaixu(kuaijie.getPaixu());
                newKuaijie.setCreateTime(new Date());
                newKuaijie.setMsgType(kuaijie.getMsgType());
                kuaijieService.addKuaijie(newKuaijie);
            }
            //复制欢迎语
//            welcomeService.deleteByUserId(copyUser.getUserId());
            List<Welcome> welcomes = welcomeService.queryWelcomeList(user.getUserId());
            for (Welcome welcome : welcomes) {
                Welcome  newWelcome = new Welcome();
                newWelcome.setUserId(copyUser.getUserId());
                newWelcome.setIsUsing(welcome.getIsUsing());
                newWelcome.setMsgType(welcome.getMsgType());
                newWelcome.setContent(welcome.getContent());
                newWelcome.setDelaySecond(welcome.getDelaySecond());
                newWelcome.setSort(welcome.getSort());
                newWelcome.setCreateTime(new Date());
                welcomeService.addWelcome(newWelcome);
            }
            //复制离线
//            lixianService.deleteByUserId(copyUser.getUserId());
            Lixian query = new Lixian();
            query.setUserId(user.getUserId());
            List<Lixian> lixianList = lixianService.selectLixianList(query);
            for (Lixian lixian : lixianList) {
                Lixian  newLixian = new Lixian();
                newLixian.setUserId(copyUser.getUserId());
                newLixian.setIsuse(lixian.getIsuse());
                newLixian.setName(lixian.getName());
                newLixian.setMsgType(lixian.getMsgType());
                newLixian.setContent(lixian.getContent());
                newLixian.setCreateTime(new Date());
                lixianService.insertLixian(newLixian);
            }
        }

        return Response.makeOKRsp().setMsg("复制成功");
    }


    @GetMapping("/queryUser")
    public ResponseResult<Object> queryUser(String code,int day){
        if (code == null) return Response.makeErrRsp("输入卡密不能为空");
        User user = userService.getUserBykamiCode(code);
        if(null == user){
            return Response.makeErrRsp("卡密信息错误");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("kefu_id",user.getUserId());

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        if (day > 0){
            calendar.add(Calendar.DATE, -(day));
            queryWrapper.ge("create_time", formatDateTime(calendar.getTime(),"yyyy-MM-dd 00:00:00"));
        }else {
            queryWrapper.ge("create_time", formatDateTime(new Date(),"yyyy-MM-dd 00:00:00"));
        }

        queryWrapper.orderByDesc("create_time");
        List<User> list = userService.list(queryWrapper);
        List<YunConfig> yunConfigList = iYunConfigService.selectYunConfigList(new YunConfig());
        String imageHost = "";
        for (YunConfig yunConfig : yunConfigList) {
            if("down".equals(yunConfig.getDictKey())){
                imageHost = yunConfig.getDictValue();
            }
        }
        for (User user1 : list){
            user1.setAvatar(imageHost + user1.getAvatar());
        }

        return Response.makeOKRsp().setData(list);

    }

    public String formatDateTime(Date date,String formatStr) {
        if (null == date) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        return format.format(date);
    }

    /**
     * 查询到期时间
     *
     * */
    @GetMapping("/queryEndTime")
    public ResponseResult<Object> queryEndTime(String kamicodes){
        if (kamicodes == null) return Response.makeErrRsp("输入卡密不能为空");
        String[] codes = kamicodes.split(",");
        List<LinkedHashMap> list = new ArrayList<>();
        for (String code : codes) {
            Code byKamicode = codeService.getCodeByKamicode(code);
            if (byKamicode != null){
                LinkedHashMap<String,Object> map = new LinkedHashMap<>();

                if("nouse".equals(byKamicode.getKamistatus())){
                    map.put("kamicode",code);
                    map.put("status","未激活");
                    map.put("days","有效期: " + byKamicode.getDays() + "天");
                }else{
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if ("uselogin".equals(byKamicode.getKamitype())){
                        User user = userService.getUserBykamiCode(code);
                        map.put("kamicode",code);
                        map.put("status","已激活");
                        map.put("days","到期时间: " + sdf.format(user.getEndTime()));
                    }else {
                        map.put("kamicode",code);
                        map.put("status","已使用");
                        String result = "";
                        if (!StringUtils.isEmpty(byKamicode.getUserId())){
                            result = "使用卡密:"+byKamicode.getUserId();
                        }
                        map.put("days","使用时间: " + sdf.format(byKamicode.getUsetime()) + result);
                    }
                }
                list.add(map);
            }else {
                LinkedHashMap<String,Object> map = new LinkedHashMap<>();
                map.put("kamicode",code);
                map.put("status","--");
                map.put("days","--");
                list.add(map);
            }
        }
        return Response.makeOKRsp(list);
    }
}
